package com.examinantsdk

import android.annotation.SuppressLint
import android.content.Context
import android.provider.Settings
import okhttp3.OkHttpClient
import java.security.KeyStore
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.util.Arrays
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager

@SuppressLint("HardwareIds")
fun getAndroidId(context: Context): String {
    val androidID = try {
        Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
    } catch (e: Exception) {
        ""
    }
    return androidID
}

fun OkHttpClient.Builder.exemptCertificate() {
    if (isExemptCertificate()) {
        try {
            this.sslSocketFactory(getSSLSocketFactory(), getX509TrustManager())
            this.hostnameVerifier(getHostnameVerifier())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

fun isExemptCertificate(): Boolean = BuildConfig.DEBUG || !BuildConfig.BUILD_PRO

private fun getTrustManager(): Array<X509TrustManager> {
    return arrayOf(object : X509TrustManager {
        override fun checkClientTrusted(chain: Array<X509Certificate?>?, authType: String?) {}
        override fun checkServerTrusted(chain: Array<X509Certificate?>?, authType: String?) {}
        override fun getAcceptedIssuers(): Array<X509Certificate?> {
            return arrayOf()
        }
    })
}

fun getSSLSocketFactory(): SSLSocketFactory {
    return try {
        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, getTrustManager(), SecureRandom())
        sslContext.socketFactory
    } catch (e: Exception) {
        e.printStackTrace()
        throw RuntimeException()
    }
}

fun getHostnameVerifier(): HostnameVerifier {
    return HostnameVerifier { _, _ -> true }
}

fun getX509TrustManager(): X509TrustManager {
    return try {
        val trustManagerFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
        trustManagerFactory.init(null as KeyStore?)
        val trustManagers = trustManagerFactory.trustManagers
        check(!(trustManagers.size != 1 || trustManagers[0] !is X509TrustManager)) {
            "Unexpected default trust managers:" + Arrays.toString(trustManagers)
        }
        trustManagers[0] as X509TrustManager
    } catch (e: Exception) {
        e.printStackTrace()
        throw RuntimeException()
    }
}